﻿using System;
using System.Diagnostics;
using System.Xml.Linq;
using EzDesk.DevHelper.DbMgr.Views;
using EzDesk.Utility.Log;
using Microsoft.SqlServer.Management.Smo;
using System.Linq;
using System.Data.Linq;

namespace EzDesk.DevHelper.DbMgr.Presenters
{
    public class DataProcessPresenter : DbMgrPresenterBase
    {
        private IDataProcessView _view;

        public DataProcessPresenter(DataProcessPanel dataProcessPanel)
        {
            this._view = dataProcessPanel;
            _logView = dataProcessPanel;
        }

        private string coreDatabaseName = "EzDeskDatabase";

        private string exportAppFunctionXmlFileName = "EzDeskAppFunctions.xml";
        private string exportFeedXmlFileName = "EzDeskFeedTemplates.xml";
        private string exportCoreInfoXmlFileName = "EzDeskCoreInfo.xml";
        private string exportAttendanceLeavesByLawXmlFileName = "EzDeskAttendanceLeavesByLaw.xml";


        private void dropAllDatabases()
        {
            Server srv = new Server(_dataSourceName);
            foreach (var databaseName in _databaseNameList)
            {
                if (srv.Databases.Contains(databaseName))
                {
                    var database = srv.Databases[databaseName];
                    if (database.UserAccess != DatabaseUserAccess.Single)
                    {
                        database.UserAccess = DatabaseUserAccess.Single;
                        database.Alter(TerminationClause.RollbackTransactionsImmediately);
                        database.Refresh();
                    }
                    database.Drop();
                    _view.WriteLine("删除数据库 " + databaseName + "成功");
                }
            }
        }

        protected void importFeedsTemplate(string xmlFileName)
        {
            using (var db = new EzDeskDatabaseDataContext(getConnectionString(coreDatabaseName)))
            {

                XElement rootElement = XElement.Load(xmlFileName);
                var feeds = rootElement.Elements();
                foreach (var feed in feeds)
                {
                    Guid id = Guid.Empty;
                    if (feed.Element("id") != null)
                    {
                        id = new Guid(feed.Element("id").Value);
                    }
                    string templateName = null;
                    if (feed.Element("name") != null)
                    {
                        templateName = feed.Element("name").Value;
                    }
                    string title = null;
                    if (feed.Element("title") != null)
                    {
                        title = feed.Element("title").Value;
                    }
                    string body = null;
                    if (feed.Element("body") != null)
                    {
                        body = feed.Element("body").Value;
                    }
                    int type = 0;
                    if (feed.Element("type") != null)
                    {
                        type = Int32.Parse(feed.Element("type").Value);
                    }
                    string templateIcon = "";
                    if (feed.Element("templateIcon") != null)
                    {
                        templateIcon = feed.Element("templateIcon").Value;
                    }

                    var feedTemplateSet = db.FeedTemplateSets.FirstOrDefault(ft => ft.Id == id);
                    if(feedTemplateSet!= null)
                    {
                        feedTemplateSet.TemplateName=templateName;
                        feedTemplateSet.Title = title;
                        feedTemplateSet.Body = body;
                        feedTemplateSet.DefaultTypeValue = type;
                        feedTemplateSet.TemplateIconName = templateIcon;
                    }
                    else
                    {
                        db.FeedTemplateSets.InsertOnSubmit(
                           new FeedTemplateSet()
                           {
                               TemplateName = templateName,
                               Id = id,
                               Title = title,
                               Body = body,
                               DefaultTypeValue = type,
                               TemplateIconName = templateIcon,
                           }
                           );   
                    }
                }
                db.SubmitChanges();
            }
            _view.WriteLine("更新Feed数据完成！");
        }

        protected void importAppFunctions(string xmlFileName)
        {
            using (var db = new EzDeskDatabaseDataContext(getConnectionString(coreDatabaseName)))
            {
                db.AppFunctionTypeSets.DeleteAllOnSubmit(db.AppFunctionTypeSets);
                db.AppFunctionSets.DeleteAllOnSubmit(db.AppFunctionSets);
                db.SubmitChanges();

                #region [ AppFunction Types ]

                // 创建 AppFunctions 类型

                Debug.WriteLine("开始创建AppFunctionType");


                XElement typeElement = XElement.Load(xmlFileName);
                var types = typeElement.Element("Types").Elements();
                foreach (var type in types)
                {
                    Guid appFunctionTypeID = Guid.Empty;
                    if (type.Element("AppFunctionTypeId") != null)
                    {
                        appFunctionTypeID = new Guid(type.Element("AppFunctionTypeId").Value);
                    }
                    string typeName = "";
                    if (type.Element("TypeName") != null)
                    {
                        typeName = type.Element("TypeName").Value;
                    }
                    string displayText = "";
                    if (type.Element("DisplayText") != null)
                    {
                        displayText = type.Element("DisplayText").Value;
                    }
                    string iconName = "";
                    if (type.Element("IconName") != null)
                    {
                        iconName = type.Element("IconName").Value;
                    }

                    int privilege = 0;
                    if (type.Element("Privilege") != null)
                    {
                        privilege = Int32.Parse(type.Element("Privilege").Value);
                    }


                    db.AppFunctionTypeSets.InsertOnSubmit(
                        new AppFunctionTypeSet()
                            {
                                Id = appFunctionTypeID,
                                TypeName = typeName,
                                DisplayText = displayText,
                                IconName = iconName,
                                Privilege = privilege

                            }
                        );
                }
                db.SubmitChanges();

                Debug.WriteLine("AppFunctionType创建完成");

                #endregion

                #region [ App Functions ]

                Debug.WriteLine("开始创建AppFunctions");
                XElement rootElement = XElement.Load(xmlFileName);
                var functions = rootElement.Element("Functions").Elements();
                foreach (var function in functions)
                {
                    Guid appFunctionId = Guid.Empty;
                    if (function.Element("AppFunctionId") != null)
                    {
                        appFunctionId = new Guid(function.Element("AppFunctionId").Value);
                    }
                    string appName = "";
                    if (function.Element("AppName") != null)
                    {
                        appName = function.Element("AppName").Value;
                    }
                    Guid functionTypeId = Guid.Empty;
                    if (function.Element("FunctionTypeId") != null)
                    {
                        functionTypeId = new Guid(function.Element("FunctionTypeId").Value);
                    }
                    Guid functionCategoryId = Guid.Empty;
                    if (function.Element("FunctionCategoryId") != null)
                    {
                        functionCategoryId = new Guid(function.Element("FunctionCategoryId").Value);
                    }
                    string title = "";
                    if (function.Element("Title") != null)
                    {
                        title = function.Element("Title").Value;
                    }
                    string description = "";
                    if (function.Element("Description") != null)
                    {
                        description = function.Element("Description").Value;
                    }
                    string iconName = "";
                    if (function.Element("IconName") != null)
                    {
                        iconName = function.Element("IconName").Value;
                    }
                    string funcUrl = "";
                    if (function.Element("FuncUrl") != null)
                    {
                        funcUrl = function.Element("FuncUrl").Value;
                    }
                    int privilege = 0;
                    if (function.Element("Privilege") != null)
                    {
                        privilege = Int32.Parse(function.Element("Privilege").Value);
                    }
                    string permissionNeed = null;
                    if (function.Element("PermissionNeed") != null)
                    {
                        permissionNeed = function.Element("PermissionNeed").Value;
                    }
                    string userAgent = "";
                    if (function.Element("UserAgent") != null)
                    {
                        userAgent = function.Element("UserAgent").Value;
                    }

                    db.AppFunctionSets.InsertOnSubmit(
                        new AppFunctionSet()
                            {
                                Id = appFunctionId,
                                AppName = appName,
                                FunctionTypeId = functionTypeId,
                                FunctionCategoryId = functionCategoryId,
                                Title = title,
                                Description = description,
                                IconName = iconName,
                                FuncUrl = funcUrl,
                                Privilege = privilege,
                                PermissionNeed = permissionNeed,
                                UserAgent = userAgent
                            }
                        );
                }
                db.SubmitChanges();

            }
            _view.WriteLine("更新AppFunctions数据完成！");

                #endregion


        }

        public void ExporttAppFunctionXml()
        {
            XElement saveXml = new XElement("AppFuntions");

            using (var db = new EzDeskDatabaseDataContext(getConnectionString(coreDatabaseName)))
            {
                XElement functionType = new XElement("Types");
                foreach (var entity in db.AppFunctionTypeSets)
                {
                    functionType.Add(new XElement("Type",
                                        new XElement("AppFunctionTypeId", entity.Id.ToString()),
                                        new XElement("TypeName", entity.TypeName),
                                        new XElement("DisplayText", entity.DisplayText),
                                        new XElement("IconName", entity.IconName),
                                        new XElement("Privilege", entity.Privilege.ToString())
                                    ));
                }

                XElement function = new XElement("Functions");
                foreach (var entity in db.AppFunctionSets)
                {
                    function.Add(new XElement("Function",
                        new XElement("AppFunctionId", entity.Id.ToString()),
                            new XElement("AppName", entity.AppName),
                            new XElement("FunctionTypeId", entity.FunctionTypeId.ToString()),
                            new XElement("FunctionCategoryId", entity.FunctionCategoryId.ToString()),
                            new XElement("Title", entity.Title),
                            new XElement("Description", entity.Description),
                            new XElement("IconName", entity.IconName),
                            new XElement("FuncUrl", entity.FuncUrl),
                            new XElement("Privilege", entity.Privilege.ToString()),
                            new XElement("PermissionNeed", entity.PermissionNeed),
                            new XElement("UserAgent", entity.UserAgent)
                        )
                        );
                }

                saveXml.Add(functionType);
                saveXml.Add(function);
            }

            saveXml.Save(exportAppFunctionXmlFileName);

            _view.WriteLine("生成 " + exportAppFunctionXmlFileName + " 成功");
            try
            {
                // 如果在开发环境下，尝试更新用于开发的文件
                CopyFileToDevEnv(exportAppFunctionXmlFileName);
            }
            catch (Exception ex)
            {
                _view.WriteLine("复制生成的文件到开发环境出错，可能是没有CheckOut " + exportAppFunctionXmlFileName + "  " + ex.Message);
            }

        }

        public void ExportFeedTemplateXml()
        {
            LogEx.TRACE("MainForm - Presenter", "开始将当前数据库内容导出到XML");

            var root = new XElement("FeedTemplates");

            using (var db = new EzDeskDatabaseDataContext(getConnectionString(coreDatabaseName)))
            {
                foreach (var entity in db.FeedTemplateSets)
                {
                    XElement feedTempalteEle = new XElement("feedTemplate");
                    feedTempalteEle.Add(new XElement("id", entity.Id.ToString()));
                    feedTempalteEle.Add(new XElement("name", entity.TemplateName));
                    feedTempalteEle.Add(new XElement("body", entity.Body));
                    feedTempalteEle.Add(new XElement("title", entity.Title));
                    feedTempalteEle.Add(new XElement("type", entity.DefaultTypeValue.ToString()));
                    feedTempalteEle.Add(new XElement("templateIcon", entity.TemplateIconName));

                    root.Add(feedTempalteEle);
                }
            }

            root.Save(exportFeedXmlFileName);

            _view.WriteLine("生成 EzDeskFeedTemplates.xml 成功");
            try
            {
                // 如果在开发环境下，尝试更新用于开发的文件
                CopyFileToDevEnv(exportFeedXmlFileName);
            }
            catch (Exception ex)
            {
                _view.WriteLine("复制生成的文件到开发环境出错，可能是没有CheckOut " + exportFeedXmlFileName + "  " + ex.Message);
            }
        }

        public void ExportCoreXml()
        {
            LogEx.TRACE("MainForm - Presenter", "开始导出基本Core信息到XML");
            var root = new XElement("CoreInfo");
            throw new NotImplementedException();
        }

        public void ImportFeedTemplates()
        {
            importFeedsTemplate(exportFeedXmlFileName);
        }

        public void ImportAppFunctions()
        {
            importAppFunctions(exportAppFunctionXmlFileName);
        }

        public void InitializeAll()
        {
            // 恢复到初始化数据

            // 1. 更新数据库架构
            //refreshAllAvailableDatabaseSchema();
            // 2. 清空数据

            // 3. 写入程序初始数据

            throw new NotImplementedException();
        }




    }
}
